package com.example.myapplication;

import  android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class exchange extends AppCompatActivity implements Runnable{

    private static final String TAG = "exchange";
    private EditText inputrmb;
    private TextView result;
    float dollarRate =0.14f;
    float euroRate =0.13f;
    float wonRate =200.80f;
    @SuppressLint("MissingInflatedId")
    Handler handler ;
    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_exchange);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        inputrmb = findViewById(R.id.v1);
        result =findViewById(R.id.v2);

        handler =new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(@NonNull Message msg){
                if(msg.what==6){
                    String str=(String) msg.obj;
                }
                super.handleMessage(msg);
            }
        };
        Log.i(TAG,"onCreate:启动线程");
        Thread t =new Thread(this);
        t.start();
    }
    public void click(View bt){
        Log.i(TAG, "click:222222222222");
        String strrmb = inputrmb.getText().toString();
        try {
            float rmb = Float.parseFloat(strrmb);
            float re = 0;
            if (bt.getId() == R.id.bt1) {
                re = rmb*dollarRate;
            } else if (bt.getId() == R.id.bt2) {
                re = rmb*euroRate;
            } else if (bt.getId() == R.id.bt3) {
                re = rmb * wonRate;
            }
            result.setText(String.valueOf(re));
        }catch (NumberFormatException e){
            Toast.makeText(this,"请输入正确的数据",Toast.LENGTH_SHORT).show();
        }
    }

    public void openConfig(View bt){
        Intent intent = new Intent(this, rmbrate.class);
        intent.putExtra("key_dollar",dollarRate);
        intent.putExtra("key_euro",euroRate);
        intent.putExtra("key_won",wonRate);

        Log.i(TAG,"openConfig:dollarRate=" + dollarRate);
        Log.i(TAG,"openConfig:euroRate=" + euroRate);
        Log.i(TAG,"openConfig:wonRate=" + wonRate);

        startActivityForResult(intent,6);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode==6&&resultCode==3){
            Bundle ret=data.getExtras();
            dollarRate=ret.getFloat("ret_dollar");
            euroRate=ret.getFloat("ret_euro");
            wonRate=ret.getFloat("ret_won");
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void run() {
        Log.i(TAG,"run");

        try{
            Thread.sleep(2000);
            URL url = null;
            try{
//                url = new URL("https://www.boc.cn/sourcedb/whpj/");
//                HttpURLConnection http =(HttpURLConnection)  url.openConnection();
//                InputStream in =http.getInputStream();
//
//                String html = inputStream2String(in);
//                Log.i(TAG,"run:html=" + html);

                Document doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/").get();
                Log.i(TAG,"run:title=" + doc.title());

                Elements tables = doc.getElementsByTag("table");
                Element table = (Element) tables.get(1);
                Elements trs = table.getElementsByTag("tr");
                trs.remove(0);
                for (Element tr : trs){
                    Elements tds = tr.children();
                    Element td1 = tds.first();
                    Element td2 = tds.get(5);
                    String str1 = td1.text();
                    String str2 = td2.text();

                    Log.i(TAG,"run"+ str1 + "==>" + str2);
                }



            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
        }
        }catch (InterruptedException e){
            throw new RuntimeException(e);
        }
        Message msg=handler.obtainMessage(6,"hello");
        handler.sendMessage(msg);
    }
    private String inputStream2String(InputStream inputStream)
        throws IOException{
        final int bufferSize =1024;
        final char[] buffer =new char[bufferSize];
        final StringBuilder out =new StringBuilder();
        Reader in = new InputStreamReader(inputStream,"UTF-8");
        while (true){
            int rsz = in.read(buffer,0,buffer.length);
            if(rsz<0)
                break;
            out.append(buffer,0,rsz);
        }
        return out.toString();
    }
}
